﻿using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utilities
{

    public class VtlHelper
    {
        private static VelocityEngine vltEngine;
        //private static VelocityContext vltContext;
        private static IContext context = null;
        public static void Init(string templateFolderPath)
        {
            vltEngine = new VelocityEngine();
            //vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            //vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath(templateFolderPath));//模板文件所在的文件夹
            //vltEngine.Init();

            //使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath(templateFolderPath));
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
            vltEngine.Init(props);
            //为模板变量赋值
            context = new VelocityContext();

        }
        public static void Put(string key, object value)
        {
            if (context == null)
            {
                context = new VelocityContext();
            }

            context.Put(key, value);//设置参数，在模板中可以通过$data来引用

        }
        public static string Reader(string templateFullName)
        {
            Template vltTemplate = vltEngine.GetTemplate(templateFullName);
            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(context, vltWriter);
            return vltWriter.GetStringBuilder().ToString();
        }

    }



}
